﻿using DocumentFormat.OpenXml.Packaging;
using OpenXmlPowerTools;
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace ExcelWordToHtml
{
    public class WordHelper
    {
        public static string ConvertToHtml(WordprocessingDocument wDoc)
        {
            int imageCounter = 0;
            string str = "";
            CoreFilePropertiesPart coreFilePropertiesPart = wDoc.CoreFilePropertiesPart;
            if (coreFilePropertiesPart != null)
            {
                string text1 = (string)Enumerable.FirstOrDefault<XElement>(PtOpenXmlExtensions.GetXDocument(coreFilePropertiesPart).Descendants(DC.title));
                string text2 = text1;
                if (text1 == null)
                {
                    string local1 = text1;
                    text2 = "";
                }
                str = text2;
            }
            WmlToHtmlConverterSettings settings1 = new WmlToHtmlConverterSettings();
            settings1.AdditionalCss = "body { margin: 1cm auto; max-width: 20cm; padding: 0; }";
            settings1.PageTitle = str;
            settings1.FabricateCssClasses = true;
            settings1.CssClassPrefix = "pt-";
            settings1.RestrictToSupportedLanguages = false;
            settings1.RestrictToSupportedNumberingFormats = false;
            settings1.ImageHandler = (imageInfo) => 
            {

                string str2;
                imageCounter++;
                string str11 = imageInfo.ContentType.Split('/', (char)(StringSplitOptions)StringSplitOptions.None)[1].ToLower();
                ImageFormat png = null;
                if (str11 == "png")
                {
                    png = ImageFormat.Png;
                }
                else if (str11 == "gif")
                {
                    png = ImageFormat.Gif;
                }
                else if (str11 == "bmp")
                {
                    png = ImageFormat.Bmp;
                }
                else if (str11 == "jpeg")
                {
                    png = ImageFormat.Jpeg;
                }
                else if (str11 == "tiff")
                {
                    str = "gif";
                    png = ImageFormat.Gif;
                }
                else if (str11 == "x-wmf")
                {
                    str = "wmf";
                    png = ImageFormat.Wmf;
                }
                if (png != null)
                {
                    str2 = null;
                    try
                    {
                        using (MemoryStream stream = new MemoryStream())
                        {
                            imageInfo.Bitmap.Save((Stream)stream, png);
                            str2 = Convert.ToBase64String(stream.ToArray());
                        }
                    }
                    catch (ExternalException)
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }
                ImageFormat format = imageInfo.Bitmap.RawFormat;
                string mimeType = ImageCodecInfo.GetImageDecoders().First(e => e.FormatID == format.Guid).MimeType;
                //string mimeType = Enumerable.First<ImageCodecInfo>(ImageCodecInfo.GetImageDecoders(), delegate (ImageCodecInfo c)
                //{
                //    return c.FormatID == format.Guid;
                //}).MimeType;
                string str4 = string.Format("data:{0};base64,{1}", mimeType, str2);
                object[] objArray1 = new object[] { new XAttribute(NoNamespace.src, str4), imageInfo.ImgStyleAttribute, (imageInfo.AltText != null) ? new XAttribute(NoNamespace.alt, imageInfo.AltText) : null };
                return new XElement(Xhtml.img, objArray1);

            };
            
            WmlToHtmlConverterSettings settings = settings1;
            XElement element = WmlToHtmlConverter.ConvertToHtml(wDoc, settings);
            object[] content = new object[] { new XDocumentType("html", null, null, null), element };
            return new XDocument(content).ToString((SaveOptions)SaveOptions.DisableFormatting);
        }

        public static string ToHtml(string filePath)
        {
            string str;
            byte[] buffer = File.ReadAllBytes(filePath);
            using (MemoryStream stream = new MemoryStream())
            {
                stream.Write(buffer, 0, buffer.Length);
                using (WordprocessingDocument document = WordprocessingDocument.Open((Stream)stream, true))
                {
                    str = ConvertToHtml(document);
                }
            }
            return str;
        }
    }
}
